import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Drawer, Form, FormProps, Input, InputNumber, Space } from 'antd';
import dayjs from 'dayjs';

import { store } from '@/store';

import { proDataRawAdd, proDataRawUpdate } from '@/services/bizApi/yuanshuishujujiekou';

import { BizObject } from '.';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values
      };
      if (args?.type === 'edit') {
        // 编辑接口
        await proDataRawUpdate({
          ...query,

          id: args?.rowData?.id
        });
      } else {
        await proDataRawAdd(query);
      }

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'add' ? '新增成功' : '编辑成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData,
              rq: dayjs(arg.rowData?.rq)
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');
      return;
    }
    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增',
          edit: '编辑',
          detail: '详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                确定
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="日期"
          name="rq"
          rules={[
            {
              required: true,
              message: '请选择日期'
            }
          ]}
        >
          <DatePicker style={{ width: '100%' }} placeholder="请选择日期" />
        </Form.Item>

        <Form.Item
          label="当日进水量"
          name="drjsl"
          rules={[
            {
              required: true,
              message: '请输入当日进水量'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入当日进水量"
          />
        </Form.Item>

        <Form.Item
          label="当日供水量"
          name="drgsl"
          rules={[
            {
              required: true,
              message: '请输入当日供水量'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入当日供水量"
          />
        </Form.Item>

        <Form.Item
          label="当日用电量"
          name="drydl"
          rules={[
            {
              required: true,
              message: '请输入当日用电量'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入当日用电量"
          />
        </Form.Item>

        <Form.Item
          label="排泥量"
          name="pnl"
          rules={[
            {
              required: true,
              message: '请输入排泥量'
            }
          ]}
        >
          <InputNumber style={{ width: '100%' }} min={0} precision={3} placeholder="请输入排泥量" />
        </Form.Item>

        <Form.Item
          label="餐厨厂"
          name="ccc"
          rules={[
            {
              required: true,
              message: '请输入餐厨厂数据'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入餐厨厂数据"
          />
        </Form.Item>

        <Form.Item
          label="固废公司"
          name="gfgs"
          rules={[
            {
              required: true,
              message: '请输入固废公司数据'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入固废公司数据"
          />
        </Form.Item>

        <Form.Item
          label="综合管理区（绿化）"
          name="zhglq"
          rules={[
            {
              required: true,
              message: '请输入综合管理区（绿化）数据'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入综合管理区（绿化）数据"
          />
        </Form.Item>

        <Form.Item
          label="市公司接驳区"
          name="sgsjbq"
          rules={[
            {
              required: true,
              message: '请输入市公司接驳区数据'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入市公司接驳区数据"
          />
        </Form.Item>

        <Form.Item
          label="桂湾"
          name="gw"
          rules={[
            {
              required: true,
              message: '请输入桂湾数据'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入桂湾数据"
          />
        </Form.Item>

        <Form.Item
          label="餐厨污水厂"
          name="ccwsc"
          rules={[
            {
              required: true,
              message: '请输入餐厨污水厂数据'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入餐厨污水厂数据"
          />
        </Form.Item>

        <Form.Item
          label="洛碛渗滤液"
          name="lqcyy"
          rules={[
            {
              required: true,
              message: '请输入洛碛渗滤液数据'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入洛碛渗滤液数据"
          />
        </Form.Item>

        <Form.Item
          label="供水合计"
          name="gshj"
          rules={[
            {
              required: true,
              message: '请输入供水合计'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入供水合计"
          />
        </Form.Item>

        <Form.Item
          label="清水池库存量"
          name="qsckcl"
          rules={[
            {
              required: true,
              message: '请输入清水池库存量'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入清水池库存量"
          />
        </Form.Item>

        <Form.Item
          label="生产异常情况说明"
          name="scycqksm"
          rules={[
            {
              required: true,
              message: '请输入生产异常情况说明'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入生产异常情况说明" />
        </Form.Item>

        <Form.Item
          label="聚氯化铝饮用水级"
          name="jlhlyysj"
          rules={[
            {
              required: true,
              message: '请输入聚氯化铝饮用水级数据'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入聚氯化铝饮用水级数据"
          />
        </Form.Item>

        <Form.Item
          label="阳离子聚丙烯酰胺2"
          name="ylzjbxya2"
          rules={[
            {
              required: true,
              message: '请输入阳离子聚丙烯酰胺2数据'
            }
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={3}
            placeholder="请输入阳离子聚丙烯酰胺2数据"
          />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
